YAHOO.namespace("cards");

var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event;

YAHOO.cards.init = function () {
    //formatter
    var cardTypeFormatter = function (elCell, oRecord) {
        if (oRecord.getData('cardType') == 'PAID') {
            elCell.innerHTML = "销售卡";
        } else if (oRecord.getData('cardType') == 'ACTIVITY') {
            elCell.innerHTML = "活动卡";
        } else if (oRecord.getData('cardType') == 'CUSTOMIZE') {
            elCell.innerHTML = "定制卡";
        }else if (oRecord.getData('cardType') == 'GIFT') {
            elCell.innerHTML = "赠送卡";
        }else {
            elCell.innerHTML = "";
        }
    };

    var periodTypeFormatter = function (elCell, oRecord) {
        if (oRecord.getData('cardValidityPeriodType') == 'Y') {
            elCell.innerHTML = "年";
        } else if (oRecord.getData('cardValidityPeriodType') == 'M') {
            elCell.innerHTML = "月";
        } else if (oRecord.getData('cardValidityPeriodType') == 'D') {
            elCell.innerHTML = "日";
        } else {
            elCell.innerHTML = "";
        }
    };


    var number_per_page_default = 20;
    var paginator = new YAHOO.widget.Paginator({
        containers: ['card-list-paging'],
        rowsPerPage: number_per_page_default,
        firstPageLinkLabel: '首页',
        previousPageLinkLabel: '上一页',
        nextPageLinkLabel: '下一页',
        lastPageLinkLabel: '末页'
    });
    var tableConfig = {
        paginator: paginator,
        MSG_EMPTY: '没有记录',
        dynamicData: true,
        initialLoad: false
    };

    var columnDefs = [
        {key: "cardId", label: '卡号'},
        {key: "cardType", label: '类型', formatter: cardTypeFormatter},
        {key: "cardParValue", label: '星币值'},
        {key: "cardActivationDeadline", label: '截止日期'},
        {key: "cardValidityPeriodType", label: '有效期类型', formatter: periodTypeFormatter},
        {key: "cardValidityPeriod", label: '有效期长度'},
        {key: "dateAdded", label: '创建时间'},
        {key: "active", label: '激活状态'}
    ];
    var dataSource = new YAHOO.util.DataSource('/ozing/job/cards.json?');
    dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    dataSource.responseSchema = {
        resultsList: 'records',
        fields: ['id', 'cardId', 'active', 'cardType', 'cardParValue', 'cardActivationDeadline', 'cardValidityPeriodType', 'cardValidityPeriod',
            'dateAdded'],
        metaFields: {
            totalRecords: 'totalRecords',
            paginationRecordOffset: "startIndex",
            paginationRowsPerPage: "pageSize"
        }
    };
    var dataTable = new YAHOO.widget.DataTable("card-list-table", columnDefs, dataSource, tableConfig);

    dataTable.showTableMessage(dataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);

    var History = YAHOO.util.History;

    var handlePagination = function (state) {
        var newState = state.page;
        History.navigate("page", newState + "");
    };

    paginator.unsubscribe("changeRequest", dataTable.onPaginatorChangeRequest);
    paginator.subscribe("changeRequest", handlePagination, dataTable, true);

    dataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
        var meta = oResponse.meta;
        oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
        oPayload.pagination = {
            rowsPerPage: meta.paginationRowsPerPage || number_per_page_default,
            recordOffset: meta.paginationRecordOffset || 0
        };
        return true;
    };

    var generateRequest = function (page) {
        page = page || 1;
        var batchId = YAHOO.util.History.getQueryStringParameter('batchId');
        var start_index = (page - 1) * number_per_page_default;
        return "start_index=" + start_index + "&num_per_page=" + number_per_page_default + "&timestamp=" + new Date().getTime() +
            "&batchId=" + batchId;
    };

    var handleHistoryNavigation = function (page) {
        dataTable.getTbodyEl().style.display = "none";
        dataTable.showTableMessage('正在加载中，请稍候...');

        dataSource.sendRequest(generateRequest(page), {
            success: function () {
                dataTable.getTbodyEl().style.display = "";
                dataTable.hideTableMessage();
                dataTable.onDataReturnReplaceRows.apply(this, arguments);
            },
            failure: function () {
                dataTable.getTbodyEl().style.display = "";
                dataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                dataTable.onDataReturnReplaceRows.apply(this, arguments);
            },
            scope: dataTable,
            argument: {} // Pass in container for population at runtime via doBeforeLoadData
        });
    };

    var initialRequest = History.getBookmarkedState("page") || "1";

    History.register("page", initialRequest, handleHistoryNavigation);

    History.onReady(function () {
        renderPage();
    });

    var renderPage = function () {
        var currentState = History.getCurrentState("page");
        handleHistoryNavigation(currentState);
    };

    // Initialize the Browser History Manager.
    YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

    return {
        ds: dataSource,
        dt: dataTable
    };

};

Event.onDOMReady(function () {
    YAHOO.cards.init();

    $('#returnCardMgtBtn').click(function(){
        window.location.href = "/ozing/card/init";
    });
});






